/*
    腾讯云对象存储上传工具
    @author Juliana
    @date 2017-12-11
 */
(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
        typeof define === 'function' && (define.amd || define.cmd) ? define(factory) :
            global.CosUtil = factory();
}(this, function () {
    'use strict';

    function CosUtil(opt) {
        var that = this;
        this.sign = ''; // 单次签名
        this.opt = $.extend({
            imgMaxSize: 0.5 * 1024 * 1024,
            fileMaxSize: 200 * 1024 * 1024,
            imgMaxWidth: 1600,
            imgQuality: 80,
            mainFolder: '',
            fileHeader: '',
            bucket: '',
            appid: '',
            region: '',
            imgCompress: 1, // 图片是否需要压缩
            ctx: '/mem',
            insertOnly: 0,//insertOnly==0 表示允许覆盖文件 1表示不允许
            bucketType: 0,// 0: 图片, 1: 文件
            batchUploadNum: 9, // 最多一批上传个数
            isGetExif: true, // 是否获取Exif
            onSelect: function (files) {
                console.info('on select:' + JSON.stringify(files));
            },
            onHandle: function (ret) {
                console.info('on handle:' + JSON.stringify(ret));
            }, // 文件处理中
            onProgress: function (file, ret) {
                console.info('upload progress:' + parseInt(ret * 100));
            }, // 文件上传进度
            onBatchComplete: function (ret) {
                console.info('batch success:' + JSON.stringify(ret));
            }, // 文件上传成功时
            onSuccess: function (ret) {
                console.info('upload success:' + JSON.stringify(ret));
            }, // 文件上传成功时
            onFailure: function (ret) {
                console.info('upload file:' + JSON.stringify(ret));
            }, // 文件上传失败时,
            onComplete: function (ret) {
            }, // 文件全部上传完毕时
        }, opt);
        this.cos = {};
    }

    function getConfig(cb) {
        $.post(this.opt.ctx + '/cos/v4/api/getConfig.do', {type: this.opt.bucketType}, function (ret) {
            if (ret.success) {
                typeof cb === 'function' && cb(ret);
            }
        });
    }

    // 获取多次上传签名
    CosUtil.prototype.getAppSign = function (callback) { // 多次签名
        var that = this;
        $.get(this.opt.ctx + '/cos/v4/api/getAppSign.do', {type: this.opt.bucketType}, function (ret) {
            if (ret.success) {
                that.sign = ret.data.sign
                callback(ret.data.sign);
            }
        });
    }
    // 压缩图片
    CosUtil.prototype.resizeImg = function (file, cb, isGetExif) {
        var self = this;
        var reader = new FileReader(), formData = new FormData();
        reader.onload = function (e) {
            var data = e.target.result;
            // 加载图片获取图片真实宽度和高度
            var image = new Image();
            self.opt.onHandle(file, '处理中');
            image.onload = function () {
                var width = image.width;
                var height = image.height;
                if (isGetExif) {
                    EXIF.getData(image, function () {
                        var exifInfo = EXIF.getAllTags(this);
                        file['exif'] = exifInfo;
                    });
                }
                if (parseInt(self.opt.imgCompress) && file.type !== 'image/gif' && (file.size > self.opt.imgMaxSize)) {
                    var maxWidth = self.opt.imgMaxWidth, maxHeight = parseInt(self.opt.imgMaxWidth / width * height);
                    var ratio = (maxWidth / maxHeight).toFixed(2);
                    file['width'] = maxWidth;
                    file['height'] = maxHeight;
                    file['ratio'] = ratio;
                    self.opt.onHandle(file, '压缩中');
                    lrz(file, {
                        width: maxWidth,
                        height: maxHeight,
                        quality: self.opt.imgQuality / 100,
                    }).then(function (rst) {
                        typeof cb === 'function' && cb(rst.file);
                    });
                } else {
                    var ratio = (width / height).toFixed(2);
                    file['width'] = width;
                    file['height'] = height;
                    file['ratio'] = ratio;
                    typeof cb === 'function' && cb(file);
                }
            };
            image.src = data;
        };
        reader.readAsDataURL(file);
    }
    CosUtil.prototype.uploadImg = function (files) {
        var that = this

        function uploadBatch() {
            var batchCount = files.length;
            if (batchCount > that.opt.batchUploadNum) {
                batchCount = that.opt.batchUploadNum
            }
            that.getAppSign(function () {
                var i = 0;

                function upload(file) {
                    var progressCb = function (ret) {
                        that.opt.onProgress(file, ret);
                    }
                    var successCb = function (ret) {
                        that.opt.onSuccess(file, ret);
                        files.splice(0, 1); // 删除上传成功的元素
                        if (++i == batchCount) {
                            that.opt.onBatchComplete(ret);
                            if (files[0]) {
                                uploadBatch();
                            } else {
                                that.opt.onComplete(ret);
                            }
                        } else {
                            if (files[0]) {
                                upload(files[0])
                            } else {
                                that.opt.onComplete(ret);
                            }
                        }
                        file = null;
                    }
                    that.resizeImg(file, function (f) {
                        file.resizeSize = f.size;
                        console.log('准备上传', file.name, file.id);
                        that.cos.uploadFile(successCb, that.opt.onFailure, progressCb, that.opt.bucket, that.opt.mainFolder + file.id + file.suffix, f, that.opt.insertOnly);
                    }, that.opt.isGetExif)
                }

                upload(files[i])
            })
        }

        uploadBatch()
    }
    CosUtil.prototype.uploadFile = function (files, isRename) {
        var that = this

        function uploadBatch() {
            var batchCount = files.length;
            if (batchCount > that.opt.batchUploadNum) {
                batchCount = that.opt.batchUploadNum
            }
            that.getAppSign(function () {
                var i = 0;

                function upload(file) {
                    var progressCb = function (ret) {
                        that.opt.onProgress(file, ret);
                    }
                    var successCb = function (ret) {
                        that.opt.onSuccess(file, ret);
                        files.splice(0, 1); // 删除上传成功的元素
                        if (++i == batchCount) {
                            that.opt.onBatchComplete(ret);
                            if (files[0]) {
                                uploadBatch();
                            } else {
                                that.opt.onComplete(ret);
                            }
                        } else {
                            if (files[0]) {
                                upload(files[0])
                            } else {
                                that.opt.onComplete(ret);
                            }
                        }
                        file = null;
                    }
                    var fileName = that.opt.mainFolder + file.name;
                    if (isRename) {
                        fileName = that.opt.mainFolder + file.id + file.suffix;
                    }
                    that.cos.uploadFile(successCb, that.opt.onFailure, progressCb, that.opt.bucket, fileName, file, that.opt.insertOnly);
                }

                upload(files[i])
            })
        }

        uploadBatch()
    }
    CosUtil.prototype.getFileStat = function (file) {
        var that = this;
        var successCb = function (ret) {
            that.opt.onSuccess(file, ret);
        }
        that.cos.getFileStat(successCb, that.opt.onFailure, that.opt.bucket, that.opt.mainFolder + file.name);
    }
    CosUtil.prototype.init = function () {
        var that = this;
        that.getConfig(function (ret) {
            var data = ret.data;
            that.opt.appid = data.app_id;
            that.opt.bucket = data.bucket;
            that.opt.region = data.region;
            that.cos = new CosCloud({
                appid: that.opt.appid, // APPID 必填参数
                bucket: that.opt.bucket, // bucketName 必填参数
                region: that.opt.region, // 地域信息 必填参数 华南地区填gz 华东填sh 华北填tj
                getAppSign: function (callback) { // 多次签名
                    callback(that.sign);
                },
                getAppSignOnce: function (callback) { // 单次签名
                    $.get(that.opt.ctx + '/cos/v4/api/getAppSignOnce.do', {type: this.opt.bucketType}, function (ret) {
                        if (ret.success) {
                            callback(ret.data.sign);
                        }
                    });
                }
            });
        });
        return that;
    }
    CosUtil.prototype.getConfig = getConfig;
    return CosUtil;
}));